/*!
 * \file cics_gateway.c
 *
 * \brief GATEWAY调用
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2015/10/07
 *
 */

#include "conntrack.h"
#include "frct_comm.h"

#include "cics_core.h"
#include "cics_comm.h"
#include "cics_mar.h"
#include "cics_gateway.h"

int cics_gateway(Conntrack *p_st_conn
                , L7session_cics *p_st_sess
                , L7_cics_packet *p_st_cics_packet
                , Frhash_header *p_st_hash_report)
{
    CICS_PRINT_INFO("cics_gateway...\n");
    char *p_language = NULL;
    unsigned int ui_language_len = 0;
    char *p_country = NULL;
    unsigned int ui_country_len = 0;
    char *p_variant = NULL;
    unsigned int ui_variant_len = 0;
    char *p_server = NULL;
    unsigned int ui_server_len = 0;

    if (bytebuff_skip(p_st_cics_packet->p_st_packet, p_st_cics_packet->ui_header_len) != FR_SUCC)
        goto error;

    if (p_st_cics_packet->ui_flow_type == APM_CICS_FLOW_HANDSHAKE)
    {
        if (cics_mar_get_utf(p_st_cics_packet, &p_language, &ui_language_len) != FR_SUCC)
            goto error;
        if (p_language != NULL)
            CICS_PRINT_ALERT("language:[%s]\n", p_language);
        if (cics_mar_get_utf(p_st_cics_packet, &p_country, &ui_country_len) != FR_SUCC)
            goto error;
        if (p_country != NULL)
            CICS_PRINT_ALERT("country:[%s]\n", p_country);

        if (p_language != NULL && p_country != NULL && p_st_sess->p_encoding == NULL)
        {
            if (strncasecmp(p_language, "zh", 2) == 0 &&
                strncasecmp(p_country, "CN", 2) == 0)
                p_st_sess->p_encoding = frstrdup("gb18030");
        }

        cics_free((void **) &p_language);
        cics_free((void **) &p_country);
        if (cics_mar_get_utf(p_st_cics_packet, &p_variant, &ui_variant_len) != FR_SUCC)
            goto error;
        if (p_variant != NULL)
        {
            CICS_PRINT_ALERT("variant:[%s]\n", p_variant);
            cics_free((void **) &p_variant);
        }

        if (p_st_cics_packet->ui_flow_version >= APM_CICS_GATEWAY_FLOW_V310)
        {
            if (cics_mar_get_utf(p_st_cics_packet, &p_server, &ui_server_len) != FR_SUCC)
                goto error;
            if (p_server != NULL)
            {
                CICS_PRINT_ALERT("server:[%s]\n", p_server);
                cics_free((void **) &p_server);
            }
        }

        /**
         * XXX: 剩余的strServerSecurityClass,abytHandshake,clientApplid,clientApplidQualifier未做解析
         */
    }
    else if (p_st_cics_packet->ui_flow_type == APM_CICS_FLOW_EXCEPTION)
    {
        // TODO
    }
    
    return FR_SUCC;
error:
    return FR_FAIL;
}
